import React, { forwardRef, useImperativeHandle } from 'react';
import { Spin, Row, Col, Space, Select, Checkbox } from 'antd';
import _ from 'lodash';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjChart, TjTable, TjSegmented } from '@/pages/ETrade/components';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { ChartTitle } from '../components';
import {
  tableColumns,
  tableFileterOptions,
  myModuls,
  handleRenderData,
  handleExportData,
} from './helper';
import {
  getMengxiMarketSupplyDemandForecastData,
  getMengxiMaintenanceInformationInfo,
} from '../services';
import { default as TreeTable } from './table';
import styles from './index.less';
import { useThemeChange } from '@/hooks';
import { useEffect } from 'react';

// 蒙西
export default forwardRef(({ formValue, marketName }, ref) => {
  const [state, setState] = useTRState({
    loading: true,
    // form
    // result
    dataSource: null, // 原始数据
    charts: _.cloneDeep(myModuls), // 模块(配置、数据)集合
    tableData: [], // 表数据
    tableFilter: tableFileterOptions.map((x) => x.value),
  });
  const { theme } = useThemeChange();

  useImperativeHandle(ref, () => ({
    onFetch,
    onExport,
  }));

  useEffect(() => {
    setTimeout(() => {
      const charts = handleRenderData(state.dataSource);
      setState({
        charts,
      });
    }, 1);
  }, [theme]);

  /** 数据处理 */
  async function onFetch() {
    setState({ loading: true });
    const [res1, res2] = await Promise.all([
      getMengxiMarketSupplyDemandForecastData(formValue),
      getMengxiMaintenanceInformationInfo(formValue),
    ]);
    const dataSource = res1?.data;
    const charts = handleRenderData(dataSource);
    const tableData = (res2?.data || []).map((x, idx) => ({
      ...x,
      id: `${idx}`,
    }));
    setState({
      dataSource,
      charts,
      tableData,
      loading: false,
    });
  }

  function onExport() {
    // 导出
    if (state.loading || !state.dataSource) return;
    const params = {
      header: [],
      data: [],
      filename: `运行数据披露-${marketName}`,
    };
    const exportDatas = [
      ...handleExportData(state.charts, state.dataSource),
      {
        name: '检修信息',
        data: [
          tableColumns.map((x) => x.name),
          ...state.tableData.map((item) => tableColumns.map(({ code }) => item[code])),
        ],
      },
    ];
    export_json_to_excel(params, exportDatas);
  }

  /** 方法 */

  /** render */
  const _renderCharts = () =>
    // 所有图
    state.charts.map((item) => {
      const right = (
        <Space size={16} wrap>
          {item.select && !!item.showTable && (
            <Select
              style={{ width: 120 }}
              value={item.select}
              options={item.selectOption}
              showArrow
              onChange={(v) => {
                item.select = v;
                setState({ charts: state.charts });
              }}
              getPopupContainer={(e) => e.parentNode}
            />
          )}
          <TjSegmented
            value={item.showTable || 0}
            options={[
              { label: '曲线', value: 0 },
              { label: '表格', value: 1 },
            ]}
            onChange={() => {
              item.showTable = Number(!item.showTable);
              setState({ charts: state.charts });
            }}
          />
        </Space>
      );

      const _columns = item?.columns || [];
      const _tableData = !!item.select
        ? item?.tableData?.[item.select] || []
        : item?.tableData || [];
      return (
        <Col span={item.span || 24} key={item.id}>
          <div className={styles.box}>
            <ChartTitle name={item.name || ''} unit={item.unit || ''} right={right} />
            <div style={{ height: 240 }}>
              {item.showTable ? (
                <div className={styles.tableWrap}>
                  <TreeTable columns={_columns} dataSource={_tableData} />
                </div>
              ) : (
                <TjChart option={item.chartOption || null} group={item.group || ''} />
              )}
            </div>
          </div>
        </Col>
      );
    });

  return (
    <div>
      <Spin spinning={state.loading}>
        <Row gutter={[16, 16]}>
          {_renderCharts()}
          <Col span={24}>
            <div className={styles.box}>
              <ChartTitle name={'检修信息'} />
              <div className={styles.tableHead}>
                <div className={styles.tableHead_name}>设备类型:</div>
                <Checkbox.Group
                  options={tableFileterOptions}
                  value={state.tableFilter}
                  onChange={(values) => setState({ tableFilter: values })}
                />
              </div>
              <TjTable
                useVirtual="auto"
                primaryKey="id"
                columns={tableColumns}
                dataSource={state.tableData.filter(({ equipmentType }) =>
                  state.tableFilter.includes(equipmentType),
                )}
              />
            </div>
          </Col>
        </Row>
        <div style={{ height: 24 }} />
      </Spin>
    </div>
  );
});
